### old match list maker

### The Plan
### Build table of current ID and old ID
### Load old date matrix
### Exchange old IDs for new IDs
### run the match reduction, make an "additional.csv" file with that reduction


load_date_index = function( ) {
  ## Building table of current ID and old ID
  tb = read.csv( "allFolks.csv", stringsAsFactors=FALSE)
  tb = tb[c("personID","IDCode")]
  tb = tb[ tb$IDCode != "", ]

  ##hack for chris english and other multiples
  tb = rbind( tb, c("CE842","CE600") )
  tb = rbind( tb, c("JM703", "JM921") )
  tb = rbind( tb, c("CE842", "CE370") )
  tb = rbind( tb, c("MA461", "MC407") )
  tb = rbind( tb, c("MA461", "AM976") )
  tb = rbind( tb, c("NT266", "NT968" ) )
 

  cat( "List of people with priors:\n" )
  print( tb )

	tb
}

old_date_finder = function( tb, old_table_name,
  event = "unknown" ) {
  
  ##redates = c("CE600","RM769","AM835")

  ## Load old date matrix & personID list
  DT = read.csv( old_table_name, stringsAsFactors=FALSE)
  nms = names(DT)[grep( "Rnd", names(DT) )]
  DTS = DT[nms]
  DTS = as.matrix(DTS)
  pids = DT$personID

  ## Exchange oldIDs for new IDs
  for ( i in 1:nrow(tb) ) {
    cat( tb[i,1], "/", tb[i,2], "  -> ", sum( DTS==tb[i,2] ), "\n" )
  }
  for ( i in 1:nrow(tb) ) {
    DTS[ DTS==tb[i,2] ] = tb[i,1]
    pids[ pids==tb[i,2] ] = tb[i,1]
  }
 
  redates = tb[,1]

  ##DT$personID

  keep=pids %in% redates
  keep
  folks = pids[ keep ]
  DTS = DTS[ keep, ]

  N = ncol( DTS )
  sel = rep( 1:nrow(DTS), N )

  folks
  DTS

  DTS = as.vector( as.matrix(DTS) )

  dats = cbind( folks[sel], DTS )

  dats = dats[ dats[,2] != "none", ]

  colnames(dats) = c("P1","P2")

  ## by now dats is a collection of pairs of known folks and random folks 
  ## we may or may not know about.

  ## cut out the random folks
  dats = dats[ dats[,2] %in% folks, ]

  ## make result table
  if ( nrow( dats ) > 0 ) {
  	dats = as.data.frame( dats )
	  dats$add = "n"
	  dats$reason = paste( "past dating at", event )
	  names(dats) = c("MatchA","MatchB","Include","WHY")

	  dats
	} else {
		NULL
	}
}


tb = load_date_index()

dats = old_date_finder( tb, "~/java/psd/old_runs/run2_csv/date_table.csv", 2 )
dats = rbind( dats, old_date_finder( tb, "~/java/psd/old_runs/run3_csv/date_table.csv", 3 ) )
dats = rbind( dats, old_date_finder( tb, "~/java/psd/old_runs/run4_csv/date_table.csv", 4 ) )

write.csv( dats, file="old_dates.csv", quote=FALSE, row.names=FALSE )

print( dats )

cat( "Found ", nrow( dats) / 2, "dates\n" )

###A = matrix( 1:80, nrow=8 )
###A
###as.numeric(A)
